#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <sys/types.h>
#include <sys/wait.h>

// child 读信息
void ReadMessage()
{
    while (true)
    {
        char buffer[1024];
        int n = read(0, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "father says > " << buffer << std::endl;
            sleep(1);
        }
        else if (n == 0)
        {
            std::cout << "arrive file end....." << std::endl;
            break;
        }
        else
        {
            std::cerr << "read error" << std::endl;
            break;
        }
    }
}

void WriteMessage(int wfd, std::string &msg)
{
    while (true)
    {
        int n = write(wfd, msg.c_str(), msg.size());
        if (n < 0)
        {
            std::cerr << "write error" << std::endl;
            break;
        }
        sleep(1);
    }
}

int main()
{
    //  创建管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    if (n < 0)
    {
        perror("pipe");
        return -1;
    }

    // 创建子进程
    pid_t id = fork();
    if (id == 0)
    {
        // child -> read
        // 关闭并不需要的fd
        close(pipefd[1]);
        dup2(pipefd[0], 0); // 重定向一下，让子进程读取默认到0读
        ReadMessage();
        close(pipefd[0]); // 通信结束
        exit(0);
    }

    // father -> write
    // 关闭不需要的fd
    close(pipefd[0]);
    std::string msg = "i am father";
    WriteMessage(pipefd[1], msg);
    close(pipefd[1]); // 通信结束
    // 等待子进程
    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if (rid > 0)
    {
        std::cout << "wait success" << std::endl;
        std::cout << "quit sig is: " << (status & 0x7f) << std::endl;
        std::cout << "quit code is: " << ((status >> 8) & 0xff) << std::endl;
    }
    std::cout << "father quit..." << std::endl;

    return 0;
}